package cn.xmall.services.cn.xmall.services.impl;

import cn.xmall.commons.models.PageQueryResult;
import cn.xmall.mappers.ItemDescMapper;
import cn.xmall.mappers.ItemMapper;
import cn.xmall.models.*;
import cn.xmall.services.ItemService;
import cn.xmall.vo.ItemVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    ItemMapper itemMapper;
    @Autowired
    ItemDescMapper itemDescMapper;

    @Override
    public ItemVO getInfoById(Long id){
        Assert.notNull(id,"id is null");
        ItemExample itemExample=new ItemExample();
        ItemExample.Criteria criteria=itemExample.createCriteria();
        criteria.andIdEqualTo(id);

        List<Item> itemList=itemMapper.selectByExample(itemExample);

        if(CollectionUtils.isEmpty(itemList)){
            return null;
        }

        Item item=itemList.get(0);
        ItemVO itemVO=new ItemVO(item);
        return itemVO;
    }

    @Override
    public String getDescById(Long id){
        Assert.notNull(id,"id is null");
        ItemDescExample itemDescExample=new ItemDescExample();
        ItemDescExample.Criteria criteria=itemDescExample.createCriteria();
        criteria.andItemIdEqualTo(id);

        List<ItemDesc> itemDescList=itemDescMapper.selectByExample(itemDescExample);

        if(CollectionUtils.isEmpty(itemDescList)){
            return null;
        }

        ItemDesc itemDesc=itemDescList.get(0);
        return itemDesc.getItemDesc();
    }

    @Override
    public PageQueryResult<ItemVO> getInfoByCidWithPage(long cid,int page,int rowNum){
        Assert.notNull(cid,"cid is null");
        ItemExample itemExample=new ItemExample();
        ItemExample.Criteria criteria=itemExample.createCriteria();
        criteria.andCidEqualTo(cid);

        PageHelper.startPage(page,rowNum);
        List<Item> itemList=itemMapper.selectByExample(itemExample);

        if(CollectionUtils.isEmpty(itemList)){
            return null;
        }

        PageInfo<Item> pageInfo = new PageInfo<>(itemList);
        PageQueryResult<ItemVO> itemVOPageQueryResult=new PageQueryResult<>();
        itemVOPageQueryResult.setTotal(pageInfo.getTotal());
        List<ItemVO> itemVOList=new ArrayList<>();

        for(Item item:itemList){
            itemVOList.add(new ItemVO(item));
        }
        itemVOPageQueryResult.setRows(itemVOList);

        return itemVOPageQueryResult;
    }

}
